<?php

namespace  App\Dao\Lsv\UploadDirDao;

use  App\Models\Mysql\Orm\Lsv\UploadDir;
use App\Common\Helper;
use App\Dao\Lsv\BaseLsv;

class Orm extends BaseLsv
{

    public function __construct()
    {
        $this->query = new UploadDir;
    }

    public  function add(array $params, string|null $admins_id)
    {
        $this->query->dir_name =  $params['dir_name'];
        $this->query->admins_id =  $admins_id;
        $this->query->dir_pid =  $params['dir_pid'] == 0 ? null : $params['dir_pid'];
        $this->query->dir_sort =  $params['dir_sort'];
        $this->query->save();
    }

    public function whereDirId(int $dir_id): Orm
    {
        $this->query = $this->query->where('dir_id', $dir_id);
        return $this;
    }

    public function whereInDirId(array $ids): Orm
    {
        $this->query = $this->query->whereIn('dir_id', $ids);
        return $this;
    }

    public function whereAdminsId(null|string $admins_id): Orm
    {
        $this->query = $this->query->where('admins_id', $admins_id);
        return $this;
    }

    public function whereAdminsIdOrNull(string $admins_id): Orm
    {
        $this->query = $this->query->where(
            function($query) use ($admins_id){
                $query->orWhere('admins_id',$admins_id)->orWhere('admins_id',null);
            }
        );
        return $this;
    }

    public  function edit(array $params)
    {
        return  $this->query->update([
            'dir_name' => $params['dir_name'],
            'dir_sort' => $params['dir_sort'],
        ]);
    }

    public  function whereIds(array $ids): Orm
    {
        $this->query =   $this->query->where(function ($query) use ($ids) {
            foreach ($ids as $val) $query->orWhere('dir_id', $val);
        });
        return $this;
    }

    public function orderByDirId(string $sort = 'ASC'): Orm
    {
        $this->query =  $this->query->orderBy('dir_id',$sort);
        return $this;
    }

    // public static function all(null|int $admins_id)
    // {
    //     $data =  static::loadOrm(UploadDir::class)->where('admins_id', $admins_id)->get([
    //         'dir_id', 'dir_name', 'dir_sort', 'dir_pid', 'admins_id'
    //     ])->toArray();

    //     return  Helper::createTree($data, 'dir_id', 'dir_pid');
    // }
}
